package com.markul.android.ui.search

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.AutoCompleteTextView
import android.widget.EditText
import android.widget.ListView
import android.widget.SimpleAdapter
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener
import com.baidu.mapapi.search.sug.SuggestionResult
import com.baidu.mapapi.search.sug.SuggestionResult.SuggestionInfo
import com.baidu.mapapi.search.sug.SuggestionSearch
import com.baidu.mapapi.search.sug.SuggestionSearchOption
import com.markul.android.MarkulApplication.Companion.context
import com.markul.android.R
import java.util.ArrayList
import java.util.HashMap
import android.content.Intent
import android.os.Handler
import android.view.MotionEvent
import androidx.core.view.get
import com.markul.android.ui.UiTool


class SearchActivity : AppCompatActivity(), OnGetSuggestionResultListener {

    private var mSuggestionSearch: SuggestionSearch? = null
    // 搜索关键字输入窗口
    private var mEditCity: String = "广州"
    private var mKeyWordsView: AutoCompleteTextView? = null
    private var mSugListView: ListView? = null
    var handler=Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        UiTool.hideStatusNavigationBar(this, true)

        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance()
        mSuggestionSearch!!.setOnGetSuggestionResultListener(this)

        // 初始化view
        mSugListView = findViewById<ListView>(R.id.sug_list)
        mKeyWordsView = findViewById<AutoCompleteTextView>(R.id.searchkey)
        mKeyWordsView!!.threshold = 1

        // 当输入关键字变化时，动态更新建议列表
        mKeyWordsView!!.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(arg0: Editable) {}
            override fun beforeTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}
            override fun onTextChanged(cs: CharSequence, arg1: Int, arg2: Int, arg3: Int) {
                if (cs.isEmpty()) {
                    return
                }
                // 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                mSuggestionSearch!!.requestSuggestion(
                    SuggestionSearchOption()
                        .keyword(cs.toString()) // 关键字
                        .city(mEditCity)
                ) // 城市
            }
        })
    }

    override fun onGetSuggestionResult(suggestionResult: SuggestionResult?) {
        if (suggestionResult == null || suggestionResult.allSuggestions == null) {
            return
        }
        val suggest: MutableList<HashMap<String, String?>> = ArrayList()
        for (info in suggestionResult.allSuggestions) {
            if (info.getKey() != null && info.getDistrict() != null && info.getCity() != null) {
                val map = HashMap<String, String?>()
                map["key"] = info.getKey()
                map["address"] = info.getAddress()
                suggest.add(map)
            }
        }
        val simpleAdapter = SimpleAdapter(
            context,
            suggest,
            R.layout.search_item,
            arrayOf("key", "address"),
            intArrayOf(R.id.sug_key, R.id.sug_address)
        )
        mSugListView!!.adapter = simpleAdapter
        mSugListView!!.setOnItemClickListener { parent, view, position, id ->
            val intent = Intent()
            intent.putExtra("key", suggestionResult.allSuggestions[position].key)
            intent.putExtra("address", suggestionResult.allSuggestions[position].address)
            intent.putExtra("lat",suggestionResult.allSuggestions[position].pt.latitude)
            intent.putExtra("lng",suggestionResult.allSuggestions[position].pt.longitude)
            setResult(1,intent)
            finish()
        }
        simpleAdapter.notifyDataSetChanged()
    }


    override fun onDestroy() {
        super.onDestroy()
        val intent = Intent()
        setResult(2,intent)
        mSuggestionSearch!!.destroy()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when (ev.getAction()) {
            MotionEvent.ACTION_UP ->
                //设置延时让画面先加载好
                handler.postDelayed(
                    Runnable {
                        UiTool.hideStatusNavigationBar(this, true)
                    }, 3000
                )
        }
        return super.dispatchTouchEvent(ev)
    }
}
